package com.flycms.web.front.rest;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.flycms.core.base.BaseController;
import com.flycms.core.entity.PagingParam;
import com.flycms.core.entity.RestDataVo;
import com.flycms.core.utils.SnowFlake;
import com.flycms.core.utils.web.utils.CommonUtils;
import com.flycms.module.offline.model.OfflineActivity;
import com.flycms.module.offline.model.OfflineActivitySign;
import com.flycms.module.offline.model.OfflineActivitySignUp;
import com.flycms.module.offline.model.OfflineActivityStatus;
import com.flycms.module.offline.service.OfflineActivityService;
import com.flycms.module.offline.service.OfflineActivitySignUpService;

/**
 *
 * <br/>Copyright 2020
 * <br/>All rights reserved
 * @author 沁言訫語
 * @version 2020年3月2日
 * @Date 2020年3月2日
 */

@RestController
@RequestMapping("/oa")
public class OfflineActivityController extends BaseController {
    
    private static final Logger logger = LogManager.getLogger(OfflineActivityController.class);
    
    @Autowired
    protected OfflineActivityService offlineService;
    
    @Autowired
    protected OfflineActivitySignUpService signUpService;
    
    @PostMapping(value = {"/list"})
    public RestDataVo getOfflineActivityList(
//            @RequestParam(value = "name", required = false) String name,
//            @RequestParam(value = "position", required = false) String position,
//            @RequestParam(value = "status", required = false) Integer status,
//            @RequestBody(required = false) PagingParam paging
            @RequestBody Map<String, String> map) {
        RestDataVo rest = new RestDataVo();
        String pageIndex = map.get("pageIndex");
        String pageSize = map.get("pageSize");
        PagingParam paging = new PagingParam();
        if (pageIndex != null) {
            paging.setPageIndex(Integer.parseInt(pageIndex));
        }
        if (pageSize != null) {
            paging.setPageSize(Integer.parseInt(pageSize));
        }
        String name = map.get("name");
        String position = map.get("position");
        String st = map.get("status");
        Integer status = null;
        if (st != null) {
            status = Integer.parseInt(st);
        }
        paging = CommonUtils.validPageParam(paging);
//        Long userId = getUserId();
        try {
            Integer s = null;
            if (Objects.equals(status, OfflineActivityStatus.ACTIVITY_SIGNING.value())
                    || Objects.equals(status, OfflineActivityStatus.ACTIVITY_END.value())
                    || Objects.equals(status, OfflineActivityStatus.ACTIVITY_ING.value())) {
                s = status;
            }
            List<OfflineActivity> offlineList = offlineService.getOfflineActivityList(name, position, s, paging.getOrderBy(),
                        paging.getOrder(), paging.getOffset(), paging.getRows());
            int count = offlineService.getOfflineActivityCount(name, position, s);
            rest = RestDataVo.PAGE(offlineList, paging.getPageIndex(), paging.getPageSize(), count);
        } catch (Exception e) {
            logger.error("", e);
            rest = RestDataVo.ERROR("获取活动列表失败");
        }
        return rest;
    }
    
    @GetMapping(value = {"/u/self/list"})
    public RestDataVo getOfflineActivitySelfList(
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "position", required = false) String position,
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
            @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        RestDataVo rest = new RestDataVo();
        PagingParam paging = CommonUtils.validParam(pageIndex, pageSize);
        Long userId = getUserId();
        try {
            Integer s = null;
            if (Objects.equals(status, OfflineActivityStatus.ACTIVITY_SIGNING.value())
                    || Objects.equals(status, OfflineActivityStatus.ACTIVITY_END.value())
                    || Objects.equals(status, OfflineActivityStatus.ACTIVITY_ING.value())) {
                s = status;
            }
            List<OfflineActivitySign> offlineList = offlineService.getSelfOfflineActivityList(userId, name, position, s,
                        paging.getOffset(), paging.getRows());
            int count = offlineService.getSelfOfflineActivityCount(userId, name, position, s);
            rest = RestDataVo.PAGE(offlineList, paging.getPageIndex(), paging.getPageSize(), count);
        } catch (Exception e) {
            logger.error("", e);
            rest = RestDataVo.ERROR("获取活动列表失败");
        }
        return rest;
    }
    
    @GetMapping(value = {"/other/list"})
    public RestDataVo getOfflineActivityOtherList(
            @RequestParam("userId") Long userId,
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "position", required = false) String position,
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
            @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        RestDataVo rest = new RestDataVo();
        PagingParam paging = CommonUtils.validParam(pageIndex, pageSize);
        if (userId == null) {
            return RestDataVo.ERROR("未传入用户ID");
        }
        try {
            Integer s = null;
            if (Objects.equals(status, OfflineActivityStatus.ACTIVITY_SIGNING.value())
                    || Objects.equals(status, OfflineActivityStatus.ACTIVITY_END.value())
                    || Objects.equals(status, OfflineActivityStatus.ACTIVITY_ING.value())) {
                s = status;
            }
            List<OfflineActivitySign> offlineList = offlineService.getSelfOfflineActivityList(userId, name, position, s,
                        paging.getOffset(), paging.getRows());
            int count = offlineService.getSelfOfflineActivityCount(userId, name, position, s);
            rest = RestDataVo.PAGE(offlineList, paging.getPageIndex(), paging.getPageSize(), count);
        } catch (Exception e) {
            logger.error("", e);
            rest = RestDataVo.ERROR("获取活动列表失败");
        }
        return rest;
    }
    
    @PostMapping(value = {"/list/calendar"})
    public RestDataVo getOfflineActivityListCalendar() {
        RestDataVo rest = new RestDataVo();
//        Long userId = 1L;
        try {
            List<OfflineActivity> offlineList = offlineService.getOfflineActivityListCalendar();
            rest = RestDataVo.OK(offlineList);
        } catch (Exception e) {
            logger.error("", e);
            rest = RestDataVo.ERROR("获取活动列表失败");
        }
        return rest;
    }
    
    @PostMapping(value = {"/info/{id}"})
    public RestDataVo getOfflineActivityInfo(@PathVariable("id") Integer id) {
        RestDataVo rest = new RestDataVo();
//        Long userId = 1L;
        try {
            OfflineActivity offline = offlineService.queryOfflineActivityById(id);
            rest = RestDataVo.OK(offline);
        } catch (Exception e) {
            logger.error("", e);
            rest = RestDataVo.ERROR("获取活动列表失败");
        }
        return rest;
    }
    
//    @PostMapping(value = {"/u/add/signup/{id}"})
//    public RestDataVo addOfflineActivitySignUp(@PathVariable("id") Integer id) {
//        RestDataVo rest = null;
//        Long userId = getUserId();
//        try {
//            OfflineActivity activity = offlineService.queryOfflineActivityById(id);
//            if (activity == null
//                    || !Objects.equals(activity.getStatus(), OfflineActivityStatus.ACTIVITY_SIGNING.value())) {
//                return RestDataVo.ERROR("活动不存在或已过报名时间");
//            }
//            OfflineActivitySignUp signup = signUpService.queryOfflineActivitySignUpById(userId, id);
//            if (signup != null) {
//                return RestDataVo.ERROR("已经报名了");
//            }
//            signup = new OfflineActivitySignUp();
//            signup.setUserId(userId);
//            signup.setOfflineId(id);
//            signup.setCreateTime(new Date());
//            signup.setStatus(OfflineActivityStatus.SING_UP_AUDIT_ING.value());
//            signUpService.addOfflineActivitySignUp(signup);
//            rest = RestDataVo.OK(signup);
//        } catch (Exception e) {
//            logger.error("", e);
//            rest = RestDataVo.ERROR("活动报名失败");
//        }
//        return rest;
//    }
    
    @PostMapping(value = {"/add/signup/{id}"})
    public RestDataVo addOfflineActivitySignUp(@PathVariable("id") Integer id,
            @Valid @RequestBody OfflineActivitySignUp signUp,
            BindingResult errors) {
        RestDataVo rest = null;
//        Long userId = getUserId();
        String validResult = CommonUtils.validParams(errors, logger);
        if (StringUtils.isNotEmpty(validResult)) {
            return RestDataVo.ERROR(validResult);
        }
        try {
            OfflineActivity activity = offlineService.queryOfflineActivityById(id);
            if (activity == null
                    || !Objects.equals(activity.getStatus(), OfflineActivityStatus.ACTIVITY_SIGNING.value())) {
                return RestDataVo.ERROR("活动不存在或已过报名时间");
            }
//            signUp.setUserId(userId);
            signUp.setId(new SnowFlake(2, 3).nextId());
            signUp.setOfflineId(id);
            signUp.setCreateTime(new Date());
            signUp.setStatus(OfflineActivityStatus.SING_UP_AUDIT_ING.value());
            signUpService.addOfflineActivitySignUp(signUp);
            rest = RestDataVo.OK(signUp);
        } catch (Exception e) {
            logger.error("", e);
            rest = RestDataVo.ERROR("活动报名失败");
        }
        return rest;
    }
    
    @GetMapping(value = {"/u/self/signup"})
    public RestDataVo getOfflineActivitySignUpInfo(
            @RequestParam(value = "offlineId", required = false) Integer offlineId,
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
            @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        RestDataVo rest = new RestDataVo();
        PagingParam paging = CommonUtils.validParam(pageIndex, pageSize);
        if (!Objects.equals(OfflineActivityStatus.SING_UP_AUDIT_PASS.value(), status)
                && !Objects.equals(OfflineActivityStatus.SING_UP_AUDIT_ING.value(), status)
                && !Objects.equals(OfflineActivityStatus.SING_UP_AUDIT_NOT_PASS.value(), status)) {
            status = null;
        }
        Long userId = getUserId();
        try {
            List<OfflineActivitySignUp> signup = signUpService.getOfflineActivitySignUpList(userId, offlineId, status,
                    paging.getOffset(), paging.getRows());
            int count = signUpService.getOfflineActivitySignUpCount(userId, offlineId, status);
            rest = RestDataVo.PAGE(signup, paging.getPageIndex(), paging.getPageSize(), count);
        } catch (Exception e) {
            logger.error("", e);
            rest = RestDataVo.ERROR("获取活动报名失败");
        }
        return rest;
    }

}
